package com.sunc.demo.order.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public HttpUtil() {
    }

    /**
     * 根据url 获取数据
     * @param url
     * @return
     */
    public static String doGet(String url) {
        StringBuffer content = new StringBuffer();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        BufferedReader br = null;

        try {
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine());
            HttpEntity e = response.getEntity();
            InputStream inputStream = e.getContent();
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String line;
            while((line = br.readLine()) != null) {
                content.append(line + "\r\n");
            }

            EntityUtils.consume(e);
        } catch (IOException var17) {
            var17.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException var16) {
                    var16.printStackTrace();
                }
            }

        }

        logger.debug(String.valueOf(content));
        return content.toString();
    }

    /**
     * 根据url 参数 是否编码参数
     * @param url
     * @param params
     * @param encodeParam
     * @return
     */
    public static HttpUtil.HttpResult doGet(String url, Map<String, String> params, Boolean encodeParam) {

        return get(buildUrl(url,params,encodeParam));
    }

    private static String buildUrl(String url,Map<String, String> params,Boolean encodeParam){
        StringBuffer queryParams = new StringBuffer();
        if(params != null) {
            Iterator var4 = params.entrySet().iterator();

            while(var4.hasNext()) {
                Entry entry = (Entry)var4.next();

                try {
                    if(encodeParam.booleanValue()) {
                        queryParams.append((String)entry.getKey()).append("=").append(URLEncoder.encode((String)entry.getValue(), "UTF-8"));
                    } else {
                        queryParams.append((String)entry.getKey()).append("=").append((String)entry.getValue());
                    }

                    queryParams.append("&");
                } catch (UnsupportedEncodingException var7) {
                    var7.printStackTrace();
                }
            }

            queryParams.deleteCharAt(queryParams.length() - 1);
        }

        return url + "?" + queryParams.toString();
    }
    public static String doGet(String url,Map<String, String> headers,Map<String, String> querys,Boolean encodeParam) {
        StringBuffer content = new StringBuffer();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(buildUrl(url,querys,encodeParam));
        for (Entry<String, String> e : headers.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }
        CloseableHttpResponse response = null;
        BufferedReader br = null;

        try {
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine());
            HttpEntity e = response.getEntity();
            InputStream inputStream = e.getContent();
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String line;
            while((line = br.readLine()) != null) {
                content.append(line + "\r\n");
            }

            EntityUtils.consume(e);
        } catch (IOException var17) {
            var17.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException var16) {
                    var16.printStackTrace();
                }
            }

        }

        logger.debug(String.valueOf(content));
        return content.toString();
    }

    public static String doPost(String url) {
        return doPost(url, (String)null);
    }

    public static String doPost(String url, String requestContent) {
        StringBuffer content = new StringBuffer();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        BufferedReader br = null;

        try {
            if(requestContent != null) {
                httpPost.setEntity(new ByteArrayEntity(requestContent.getBytes()));
            }

            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine());
            HttpEntity e = response.getEntity();
            InputStream inputStream = e.getContent();
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String line;
            while((line = br.readLine()) != null) {
                content.append(line + "\r\n");
            }

            EntityUtils.consume(e);
        } catch (IOException var18) {
            var18.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }

        }

        logger.debug(String.valueOf(content));
        return content.toString();
    }

    public static byte[] getSmallFile(String url) {
        byte[] buffer = new byte[1024];
        byte[] fileBytes = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        Object br = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            response = httpClient.execute(httpGet);
            HttpEntity e = response.getEntity();
            InputStream inputStream = e.getContent();

            int length;
            while((length = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }

            fileBytes = bos.toByteArray();
            EntityUtils.consume(e);
        } catch (IOException var23) {
            var23.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    ((BufferedReader)br).close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }

            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException var21) {
                    var21.printStackTrace();
                }
            }

        }

        return fileBytes;
    }

    public static String postWithParams(String url, Map<String, String> params) {
        StringBuffer content = new StringBuffer();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        BufferedReader br = null;

        try {
            if(params != null) {
                ArrayList e = new ArrayList();
                Iterator inputStream = params.entrySet().iterator();

                while(inputStream.hasNext()) {
                    Entry line = (Entry)inputStream.next();
                    e.add(new BasicNameValuePair((String)line.getKey(), (String)line.getValue()));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(e, "UTF-8"));
            }

            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine());
            HttpEntity e1 = response.getEntity();
            InputStream inputStream1 = e1.getContent();
            br = new BufferedReader(new InputStreamReader(inputStream1, "UTF-8"));

            String line1;
            while((line1 = br.readLine()) != null) {
                content.append(line1 + "\r\n");
            }

            EntityUtils.consume(e1);
        } catch (IOException var18) {
            var18.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }

        }

        logger.debug(String.valueOf(content));
        return content.toString();
    }



    public static HttpUtil.HttpResult post(String url, Map<String, String> params) {
        HttpUtil.HttpResult httpResult = new HttpUtil().new HttpResult();
        byte[] buffer = new byte[1024];
        if(logger.isInfoEnabled()) {
            logger.info("[http][post][request]" + url);
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        Object br = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            if(params != null) {
                ArrayList e = new ArrayList();
                Iterator inputStream = params.entrySet().iterator();

                while(inputStream.hasNext()) {
                    Entry length = (Entry)inputStream.next();
                    e.add(new BasicNameValuePair((String)length.getKey(), (String)length.getValue()));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(e, "UTF-8"));
            }

            response = httpClient.execute(httpPost);
            httpResult.setStatusCode(Integer.valueOf(response.getStatusLine().getStatusCode()));
            HttpEntity e1 = response.getEntity();
            InputStream inputStream1 = e1.getContent();

            int length1;
            while((length1 = inputStream1.read(buffer)) != -1) {
                bos.write(buffer, 0, length1);
            }

            httpResult.setContent(bos.toByteArray());
            httpResult.setContentLength(e1.getContentLength());
            if(e1.getContentEncoding() != null) {
                httpResult.setContentEncoding(e1.getContentEncoding().getValue());
            }

            if(e1.getContentType() != null) {
                httpResult.setContentType(e1.getContentType().getValue());
            }

            EntityUtils.consume(e1);
            if(logger.isInfoEnabled()) {
                logger.info("[http][post][response]" + new String(httpResult.getContent()));
            }
        } catch (IOException var24) {
            var24.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    ((BufferedReader)br).close();
                } catch (IOException var23) {
                    var23.printStackTrace();
                }
            }

            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }

        }

        return httpResult;
    }


    public static HttpUtil.HttpResult get(String url) {
        HttpUtil.HttpResult httpResult = new HttpUtil().new HttpResult();
        byte[] buffer = new byte[1024];
        if(logger.isInfoEnabled()) {
            logger.info("[http][get][request]" + url);
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        Object br = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            response = httpClient.execute(httpGet);
            httpResult.setStatusCode(Integer.valueOf(response.getStatusLine().getStatusCode()));
            HttpEntity e = response.getEntity();
            InputStream inputStream = e.getContent();

            int length;
            while((length = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }

            httpResult.setContent(bos.toByteArray());
            httpResult.setContentLength(e.getContentLength());
            if(e.getContentEncoding() != null) {
                httpResult.setContentEncoding(e.getContentEncoding().getValue());
            }

            if(e.getContentType() != null) {
                httpResult.setContentType(e.getContentType().getValue());
            }

            EntityUtils.consume(e);
            if(logger.isInfoEnabled()) {
                logger.info("[http][get][response]" + new String(httpResult.getContent()));
            }
        } catch (IOException var23) {
            var23.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    ((BufferedReader)br).close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }

            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException var21) {
                    var21.printStackTrace();
                }
            }

        }

        return httpResult;
    }

    public static String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;

                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException var4) {
                    var4.printStackTrace();
                }

                ipAddress = inet.getHostAddress();
            }
        }

        if(ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }

        return ipAddress;
    }

    public class HttpResult {
        private Integer statusCode;
        private String contentType;
        private long contentLength;
        private String contentEncoding;
        private byte[] content;

        public HttpResult() {
        }

        public String getContentType() {
            return this.contentType;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }

        public long getContentLength() {
            return this.contentLength;
        }

        public void setContentLength(long contentLength) {
            this.contentLength = contentLength;
        }

        public String getContentEncoding() {
            return this.contentEncoding;
        }

        public void setContentEncoding(String contentEncoding) {
            this.contentEncoding = contentEncoding;
        }

        public byte[] getContent() {
            return this.content;
        }

        public void setContent(byte[] content) {
            this.content = content;
        }

        public Integer getStatusCode() {
            return this.statusCode;
        }

        public void setStatusCode(Integer statusCode) {
            this.statusCode = statusCode;
        }
    }
}
